package top.jacktgq.hsp.netty.groupchat.v1;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import top.jacktgq.utils.LogUtils;

import java.util.Scanner;

/**
 * @Author CandyWall
 * @Date 2020/11/12--20:43
 * @Description 使用netty实现群聊客户端
 */
public class GroupChatClient {
    private final String host;
    private final int port;

    public GroupChatClient(String host, int port) {
        this.host = host;
        this.port = port;
    }

    private void run() {
        NioEventLoopGroup eventExecutors = new NioEventLoopGroup(1);
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(eventExecutors)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        //得到Pipeline
                        ChannelPipeline pipeline = ch.pipeline();
                        //传输String类型的消息，必须要添加String的编解码器，否则，消息无法传输
                        //向Pipeline中加入一个解码器
                        pipeline.addLast("decoder", new StringDecoder());
                        //在Pipeline中加入一个编码器
                        pipeline.addLast("encoder", new StringEncoder());
                        //在Pipeline中加入自己的业务处理Handler
                        pipeline.addLast(new top.jacktgq.hsp.netty.groupchat.v1.GroupChatClientHandler());
                    }
                });
        try {
            ChannelFuture channelFuture = bootstrap.connect(host, port).sync();
            //得到Channel
            Channel channel = channelFuture.channel();
            System.out.println(LogUtils.getCurrentTime() + " " + channel.remoteAddress() + " 准备好了...");

            //客户端需要输入信息，创建一个扫描器
            Scanner scanner = new Scanner(System.in);
            while (scanner.hasNextLine()) {
                String msg = scanner.nextLine();
                //通过channel发送到服务器端
                channel.writeAndFlush(msg);
            }

            //给关闭的通道进行监听
            //channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            eventExecutors.shutdownGracefully();
        }

    }

    public static void main(String[] args) {
        new GroupChatClient("127.0.0.1", 8888).run();
    }
}
